#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/ethernet.h>
#include <netpacket/packet.h>
#include <netinet/ip.h>
#include <string.h>

#define BUFSIZE 2048

int main() {

    int sockfd;
    char rcvbuf[BUFSIZE]; 
    struct sockaddr_ll dstaddr;

    if(-1 == (sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)))) {
        perror("socket");
        return -1;
    }

    memset(&dstaddr,0, sizeof(dstaddr));
    while(1) {
        int n, etype,packetlen,protype,iphrlen;
        struct ip *iphr;
        socklen_t socklen = sizeof(dstaddr);
        n = recvfrom(sockfd, rcvbuf, BUFSIZE, 0 , (struct sockaddr *)&dstaddr, &socklen);
        if (n < 0 ){
            perror("recvfrom");
            return -1;
        }
        struct ether_header *eth = (struct ether_header *) rcvbuf;
        etype = ntohs(eth->ether_type);
        printf("etype = %d\n", etype);
        switch(etype) {
            case ETH_P_IP:
                iphr = (struct ip *)(rcvbuf + sizeof(struct ether_header));
                iphrlen = iphr->ip_hl << 2;
                packetlen = ntohs(iphr->ip_len);
                protype = iphr->ip_p;
                printf("iphrlen = %d, packetlen= %d, protype = %d\n", iphrlen, packetlen, protype);
            break;
        }
    }

    return 0;
}